package com.mojian.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 文章浏览记录服务
 * 用于记录用户的文章浏览行为，为个性化推荐提供数据支持
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ArticleViewRecordServiceImpl {

    private final JdbcTemplate jdbcTemplate;

    /**
     * 记录用户文章浏览
     * @param userId 用户ID
     * @param articleId 文章ID
     * @param readTime 阅读时间(秒)
     */
    public void recordArticleView(Long userId, Long articleId, Integer readTime) {
        try {
            // 1. 记录浏览历史
            recordArticleViewHistory(userId, articleId, readTime);
            
            // 2. 更新常看文章统计
            updateFrequentArticle(userId, articleId);
            
            // 3. 更新常看标签统计
            updateFrequentTags(userId, articleId);
            
            // 4. 更新文章浏览量
            updateArticleViewCount(articleId);
            
        } catch (Exception e) {
            log.error("记录用户文章浏览失败: userId={}, articleId={}", userId, articleId, e);
        }
    }

    /**
     * 记录浏览历史
     */
    private void recordArticleViewHistory(Long userId, Long articleId, Integer readTime) {
        // 获取文章分类ID
        Integer categoryId = jdbcTemplate.queryForObject(
            "SELECT category_id FROM sys_article WHERE id = ?", 
            Integer.class, 
            articleId
        );
        
        if (categoryId == null) {
            log.warn("文章不存在: articleId={}", articleId);
            return;
        }
        
        // 插入浏览记录
        jdbcTemplate.update(
            "INSERT INTO sys_user_article_view (user_id, article_id, category_id, read_time, create_time) VALUES (?, ?, ?, ?, ?)",
            userId, articleId, categoryId, readTime, LocalDateTime.now()
        );
    }
    
    /**
     * 更新常看文章统计
     */
    private void updateFrequentArticle(Long userId, Long articleId) {
        // 检查是否已有记录
        Integer count = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM sys_user_frequent_article WHERE user_id = ? AND article_id = ?", 
            Integer.class, 
            userId, articleId
        );
        
        LocalDateTime now = LocalDateTime.now();
        
        if (count != null && count > 0) {
            // 更新现有记录
            jdbcTemplate.update(
                "UPDATE sys_user_frequent_article SET view_count = view_count + 1, last_view_time = ?, update_time = ? WHERE user_id = ? AND article_id = ?",
                now, now, userId, articleId
            );
        } else {
            // 创建新记录
            jdbcTemplate.update(
                "INSERT INTO sys_user_frequent_article (user_id, article_id, view_count, last_view_time, create_time, update_time) VALUES (?, ?, 1, ?, ?, ?)",
                userId, articleId, now, now, now
            );
        }
    }
    
    /**
     * 更新常看标签统计
     */
    private void updateFrequentTags(Long userId, Long articleId) {
        // 获取文章标签
        List<Map<String, Object>> tags = jdbcTemplate.queryForList(
            "SELECT tag_id FROM sys_article_tag WHERE article_id = ?", 
            articleId
        );
        
        if (tags.isEmpty()) {
            return;
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        // 更新每个标签的浏览次数
        for (Map<String, Object> tag : tags) {
            Integer tagId = ((Number) tag.get("tag_id")).intValue();
            
            // 检查是否已有记录
            Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_user_frequent_tag WHERE user_id = ? AND tag_id = ?", 
                Integer.class, 
                userId, tagId
            );
            
            if (count != null && count > 0) {
                // 更新现有记录
                jdbcTemplate.update(
                    "UPDATE sys_user_frequent_tag SET view_count = view_count + 1, update_time = ? WHERE user_id = ? AND tag_id = ?",
                    now, userId, tagId
                );
            } else {
                // 创建新记录
                jdbcTemplate.update(
                    "INSERT INTO sys_user_frequent_tag (user_id, tag_id, view_count, create_time, update_time) VALUES (?, ?, 1, ?, ?)",
                    userId, tagId, now, now
                );
            }
        }
    }
    
    /**
     * 更新文章浏览量
     */
    private void updateArticleViewCount(Long articleId) {
        jdbcTemplate.update(
            "UPDATE sys_article SET view_count = view_count + 1 WHERE id = ?", 
            articleId
        );
    }
} 